package com.chuangjian.hire.common.dto;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chuangjian.hire.common.exceptionEnum.InnerExceptionEnum;
import com.chuangjian.hire.common.exption.ApiException;
import com.chuangjian.hire.common.exption.ExceptionEnum;
import lombok.Data;

import java.io.Serializable;

@Data
public class R<T> implements Serializable {


    private static final long serialVersionUID = 1L;

    public static final int SUCCESS = 0;

    /**
     * [0] 请求正常
     * (0 -  Integer.MAX_VALUE) 业务错误号码
     * [Integer.MAX_VALUE] 特殊数据不需要包装
     */
    private Integer errCode;
    /**
     * 错误消息
     */
    private String msg;
    /**
     * 正常时候数据类型
     */
    private T data;

    private R() {
        errCode = SUCCESS;
    }

    public R(T data) {
        this();
        this.data = data;
    }

    public static R success(Object data) {
        return new R(data);
    }

    public R(T data, String msg) {
        this();
        this.data = data;
        this.msg = msg;
    }

    public R(Integer errCode, String msg, T data) {
        this(data, msg);
        this.errCode = errCode;
    }

    public R(ApiException e) {
        errCode = e.getErrCode();
        msg = e.getMessage();
    }

    public R(ExceptionEnum exceptionEnum) {
        errCode = exceptionEnum.getCode();
        msg = exceptionEnum.getMessage();
    }

    public static <T> R.RBuilder<T> builder() {
        return new R.RBuilder();
    }

    public static class RBuilder<T> {
        private Integer errCode;
        private String msg;
        private T data;

        RBuilder() {
        }

        public R.RBuilder<T> errCode(Integer errCode) {
            this.errCode = errCode;
            return this;
        }

        public R.RBuilder<T> msg(String msg) {
            this.msg = msg;
            return this;
        }

        public R.RBuilder<T> data(T data) {
            this.data = data;
            return this;
        }

        public R<T> build() {
            if (errCode == null) {
                errCode = SUCCESS;
            }
            if (errCode == SUCCESS && StringUtils.isNotBlank(msg)) {
                throw new ApiException(InnerExceptionEnum.WRAPPER_ERROR);
            }
            return new R(this.errCode, this.msg, this.data);
        }
    }
}
